<template>
  <section class="cart">
    课程：<input type="text" name="" v-model="course"/>
    <hr style="border-color: transparent"/>
    价钱：<input type="text" name="" v-model="price"/>
    <button @click="addCourse">添加商品</button>
    <ul class="title">
      <li v-for="(item, index) of classList" :key="index">
        课程名称：{{item.text}}----价格：{{item.price}}
        <button @click="addCart(index)">添加到购物车</button>
      </li>
    </ul>
    <p>购物车</p>
    <table>
      <thead>
      <tr>
        <th>选中</th>
        <th>课程</th>
        <th>数量</th>
        <th>价格</th>
      </tr>
      </thead>
     <tbody>
       <tr  v-for="(item, index) of cartArry" :key="index">
         <td><input type="checkbox" v-model="item.active"/></td>
         <td>{{item.text}}</td>
         <td>
           <span @click="reduceCount(index)">-</span>
           {{item.count}}
           <span @click="increaseCount(index)">+</span>
         </td>
         <td>{{item.price * item.count}}</td>
       </tr>
     <tr>
       <td colspan="2">
         <input type="checkbox" @click="itemAct" v-model="itemActive"/>
         选中的课程：{{activeCount}}/{{count}}
       </td>
       <td colspan="2">
         需付金额：{{totalPrice}}
         <button @click="deleteCart">清空购物车</button>
       </td>
     </tr>
     </tbody>
    </table>
  </section>
</template>

<script>
export default {
  name: 'Cart',
  data () {
    return {
      itemActive: false,
      course: '',
      price: '',
      classList: [
        {
          text: 'js',
          price: 20,
          id: 0
        },
        {
          text: 'css',
          price: 50,
          id: 1
        },
        {
          text: 'html',
          price: 40,
          id: 2
        },
        {
          text: 'vue',
          price: 80,
          id: 3
        }
      ],
      cartArry: []
    }
  },
  computed: {
    activeCount () { // 选中的商品数量
      return this.cartArry.filter(v => v.active).length // 过滤，判断其中active为true的数量并返回
    },
    count () { // 全部商品数量
      return this.cartArry.length
    },
    totalPrice () {
      let total = 0
      this.cartArry.forEach(v => { // es6循环
        if (v.active) {
          total += v.price * v.count // 因为是循环 所以必须是 +=
        }
      })
      return total
    }
  },
  methods: {
    deleteCart () { // 清楚购物车所有物品
      if (window.confirm('是否清空购物车')) {
        this.cartArry = []
      }
    },
    itemAct () { // 点击全选按钮
      if (this.activeCount == this.count) {
        this.cartArry.forEach(v => { // es6循环
          return (v.active = false)
        })
      } else {
        this.cartArry.forEach(v => { // es6循环
          return (v.active = true)
        })
      }
    },
    addCourse () { // 点击提交给数组
      this.classList.push({
        text: this.course,
        price: this.price
      })
      this.course = ''
      this.price = ''
    },
    addCart (index) { // 点击添加到购物车
      let goods = this.classList[index]
      let result = this.cartArry.find(v => v.text === goods.text) // 判断cartArry中寻找v.text是否等于goods中的text，如果等于则数量加以
      if (result) {
        result.count += 1
      } else {
        this.cartArry.push({ ...goods, count: 1, active: true })
      }
    },
    // 减少购物车商品数量
    reduceCount (ind) {
      if (this.cartArry[ind].count > 1) {
        this.cartArry[ind].count --
      } else {
        if (window.confirm(`是否删除${this.cartArry[ind].text}?`)) {
          this.cartArry.splice(ind, 1) // 删除数组 下标是ind，删除一个
        }
      }
    },
    // 增加购物车商品数量
    increaseCount (ind) {
      this.cartArry[ind].count ++
    }
  },
  watch: {
    // 监听购物车数组，每当监听到改变就存进本地存储做数据持久化cd j
    cartArry: { // 深度监听
      handler () {
        window.localStorage.setItem('cart', JSON.stringify(this.cartArry)) // JSON.stringify()转换为一个JSON字符串。
        // 全选 反选
        if (this.activeCount < this.cartArry.length) {
          this.itemActive = false
        } else {
          this.itemActive = true
        }
      },
      deep: true // 开启深度监听
    }
  },
  created () {
    console.log(window.localStorage.getItem('cart'))
    this.cartArry = JSON.parse(window.localStorage.getItem('cart')) || [] // JSON.parse() 一个JSON字符串转换为对象。如果为空那就 用|| []
  }
}
</script>

<style lang="stylus" scoped>
  .cart
    ul
      li
        font-size 18px
  table
    width 100%
    text-align center
    th, td
      font-size 16px
      border 1px solid green
</style>
